package edu.nf.llmtest.service.impl;

import com.fasterxml.jackson.databind.ObjectMapper;
import edu.nf.llmtest.common.enumeration.RedisKeyEnum;
import edu.nf.llmtest.mapper.TypeMapper;
import edu.nf.llmtest.model.entity.Type;
import edu.nf.llmtest.service.TypeService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * @ Author bin
 * @ Create  2025/11/13 11:30
 **/
@Service
@RequiredArgsConstructor
@Slf4j
public class TypeServiceImpl implements TypeService {
    private final TypeMapper typeMapper;
    private final RedisTemplate<String, Object> redisTemplate;
    private final ObjectMapper mapper;
    @Override
    public List<Type> SysnType() {
        List<Type> types = typeMapper.listType();
        redisTemplate.opsForList().leftPush(RedisKeyEnum.TYPE_PERFIX.getValue(), types);
        return types;
    }

    public List<Type> listTypeFromRedis() {
        List<Type> types = new ArrayList<>();
        List<Object> typesRedis = redisTemplate.opsForList().range(RedisKeyEnum.TYPE_PERFIX.getValue(), 0, -1);


        if (typesRedis != null && !typesRedis.isEmpty()){
            for (Object obj : typesRedis) {
                if (obj instanceof Type) {
                    types.add((Type) obj);
                } else if (obj instanceof List<?>) {
                    // 有时候 Redis 反序列化成 List<Type>
                    for (Object inner : (List<?>) obj) {
                        if (inner instanceof Type) {
                            types.add((Type) inner);
                        }
                    }
                } else {
                    System.out.println("⚠️ Redis中的对象不是Type类型: " + obj.getClass());
                }
            }
            return types;
        }
        return SysnType();
    }

    @Override
    public Integer getTypeIdByName(String name) {
        return typeMapper.getTypeIdByName(name);
    }
}
